/*
** VFORMS v1.0a
** Script para validacao facil de formularios
** Desenvolvido por Samuel Corradi - http://www.samuelcorradi.com.br
** Licenciado sob Creative Commons by-sa
** http://creativecommons.org/licenses/by-sa/2.5/br/
*/

/***************************************
** inicio definicao de mascaras para os campos
***************************************/

mascaras={
	"vMaskNumero":["§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§"],
	"vMaskLetra":["!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"],
	"vMaskTelefone":["(§§) §§§§-§§§§"],
	"vMaskCPF":["§§§.§§§.§§§-§§"],
	"vMaskData":["§§/§§/§§§§"],
	"vMaskHora":["§§:§§"],
	"vMaskCEP":["§§§§§-§§§"],
	"vMaskCartao":["§§§§ §§§§ §§§§ §§§§"]
}

/***************************************
** inicio funcoes de validacao
***************************************/

function validaCPF(cpf) {
	if (cpf.length < 11) return false
	var nonNumbers = /\D/
	if (nonNumbers.test(cpf))return false
	if (cpf == "00000000000" || cpf == "11111111111" ||
		cpf == "22222222222" || cpf == "33333333333" ||
		cpf == "44444444444" || cpf == "55555555555" ||
		cpf == "66666666666" || cpf == "77777777777" ||
		cpf == "88888888888" || cpf == "99999999999")
			return false
	var a = []
	var b = new Number
	var c = 11
	for (i=0; i<11; i++){
			a[i] = cpf.charAt(i)
			if (i < 9) b += (a[i] * --c)
	}
	if ((x = b % 11) < 2) {a[9] = 0} else {a[9] = 11-x}
	b = 0
	c = 11
	for (y=0; y<10; y++) b += (a[y] * c--)
	if ((x = b % 11) < 2) {a[10] = 0} else {a[10] = 11-x}
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))return false
	return true
}

function vCPF(t) {
	try {
		if(t=="")return true
		return validaCPF(t.replace(/\D/g,""))
	}catch(e){alert(e)}
}

function vNumero(t) {
	return t.replace(/\d*/,"")==""
}

function vObrigatorio(t) {
	return t!=""
}

function vEmail(t) {
	return t.replace(/^\w[\w\.\+-]+@\w[\w\.\+-]+\.\w\w+$/,"")==""
}

function vCEP(t) {
	return t.replace(/^\d{5}-\d{3}$/,"")==""
}

function vConfirma(t,i){
	return i.value==i.form.elements[i.name+"2"].value
}

function vData(t) {
	if(t=="")return true
	var dat=/^[0123]?\d\/[01]?\d\/\d{4}$/
	if(!dat.test(t))return false
	dat=t.split("/")
	var d=new Date()
	d.setFullYear(parseFloat(dat[2]))
	d.setMonth(parseFloat(dat[1])-1)
	d.setDate(parseFloat(dat[0]))
	return d.getMonth()==parseFloat(dat[1])-1
}

validadores={
	"vNumero":vNumero,
	"vEmail":vEmail,
	"vCPF":vCPF,
	"vCEP":vCEP,
	"vConfirma":vConfirma,
	"vData":vData,
	"vObrigatorio":vObrigatorio
}

erros={
	"vNumero":"o campo permite apenas n�meros",
	"vEmail":"digite corretamente o e-mail",
	"vCEP":"digite corretamente o CEP",
	"vCPF":"n�mero de CPF inv�lido",
	"vConfirma":"digite corretamente a confirma��o",
	"vData":"digite corretamente a data",
	"vObrigatorio":"o campo precisa ser preenchido"
}

/***************************************
** inicio dos codigos que fazem tudo funcionar
** nao eh necessario alterar nada a partir daqui
***************************************/

function showErros(er){
	var txterr="Por favor, corrija os seguintes erros:\n"
	for(var i=0;i<er.length;i++){
                $(er[i][0]).addClass('formee-error');
		txterr += $.trim(er[i][0].parentNode.innerHTML.replace(/<[^>]*>| *: */g,"")) + " "+er[i][1]+"\n"
		er[i][0].parentNode.className+=" vErro"
	}
        $('#error').css('display', "");
        $('#error').html(txterr);
}

function validaForm() {
	this.ferros=[]
	$(this).find("label")
		.removeClass("vErro")
		.each(function() {
		var vals=this.className.split(" ")
		for(var i=0;i<vals.length;i++)
			try {
				var fn=validadores[vals[i]];
				var inp=$(this).attr("for");
				inp=$("#"+inp).get()[0];
				if(!fn(inp.value,inp)) {
					$(this).parents("form")[0].ferros.push([inp,erros[vals[i]]])
				}
			} catch(e){}
	  })
	if(this.ferros.length>0) {
		showErros(this.ferros)
		return false
	}
}

function mascarar(campo, $evento) {
	var labelTarget = campo.getAttribute('id');
	lbl = $("[for="+labelTarget+"]").attr('class');
	var vals=lbl.split(" ");
	for(var j=0; j<vals.length; j++) {
		try {
			func = mascaras[vals[j]];
		} catch(e) {}
	}
	if(func) {
		mask = func[0];
		$tecla = $evento.which;
		if ($tecla == null) $tecla = $evento.keyCode;
		$teclasPermitidas = Array(0, 8, 13);
		for ($i=0; $i < $teclasPermitidas.length; $i++) {
			if ($tecla == $teclasPermitidas[$i]) return true;
		}
		string = campo.value;
		$i = string.length;
		if ($i < mask.length) {
			if (mask.charAt($i) == '�') {
				return ($tecla > 47 && $tecla < 58);
			} else {
				if (mask.charAt($i) == '!') {
					return true;
				}
				for (c = $i; c < mask.length; c++) {
					if (mask.charAt(c) != '�' && mask.charAt(c) != '!') {
						campo.value = campo.value + mask.charAt(c);
					} else if (mask.charAt(c) == '!') {
						return true;
					} else {
						return ($tecla > 47 && $tecla < 58);
					}
				}
			}
		} else return false;
	}
}

$(function() {
	$('form.vForms')
	.submit(validaForm)
	.find('input')
		.keypress( function(e) {return mascarar(this, e)} )
});
